import { load, request, htmlToString } from '../common_node.js'

const source = {
  "id": "free_book_js/12",
  "name": "妙笔阁",
  "portalUrl": "https://www.mbgbook.com",
  "searchBaseUrl": "https://www.mbgbook.com",
  "bookBaseUrl": "https://www.mbgbook.com",
  "active": true
};


async function searchBook(keyword, pageNum) {
  function getBoolList($) {
    const bookArr = [];
    if ($('#maininfo').length > 0) {//存在目录
      bookArr.push({
        name: $("meta[property='og:novel:book_name']").attr('content'),
        author: $("meta[property='og:novel:author']").attr('content'),
        path: $("meta[property='og:novel:read_url']").attr('content').replace(source.bookBaseUrl, ''),
        sourceId: source.id
      });
    } else {
      const alistboxArr = $(".grid tr");
      alistboxArr.each(function (index, elem) {
        if (index != 0) {
          let tds = $(this).find("td");
          let nameAndPath = tds.eq(0).find("a");
          bookArr.push({
            name: nameAndPath.text(),
            author: tds.eq(2).text(),
            path: nameAndPath.attr('href').replace(source.bookBaseUrl, ''),
            sourceId: source.id
          });
        }
      })
    }
    return bookArr;
  }

  let url = source.searchBaseUrl + '/modules/article/search.php?searchkey=' + keyword;
  var html = await (await request(url, { urlEncode: 'gb2312', decode: 'gbk' })).text();
  var doc = load(html);
  var bookArr = getBoolList(doc);

  return {
    size: bookArr.length,
    pageNum: 1,
    pages: 1,
    sourceId: source.id,
    keyword: keyword,
    bookList: bookArr
  };
}

async function bookDetails(path) {
  var html = await (await request(source.bookBaseUrl + path, { decode: 'gbk' })).text();
  let $ = load(html);

  return {
    name: $("meta[property='og:novel:book_name']").attr('content'),
    author: $("meta[property='og:novel:author']").attr('content'),
    path: path,
    sourceId: source.id,
    intro: $("meta[property='og:description']").attr('content'),
    coverUrl: $("#fmimg img").attr('src'),
    type: $("meta[property='og:novel:category']").attr('content'),
  };
}

async function bookCatalog(path) {
  var html = await (await request(source.bookBaseUrl + path, { decode: 'gbk' })).text();
  var $ = load(html);
  const chapters = $('#list dt:eq(1)').nextAll('dd').find('a');
  let index = 0;
  let catalog = [];
  chapters.each(function (i, elem) {
    var item = $(this)
    catalog.push({
      index: index++,
      title: item.text(),
      path: item.attr("href")
    });
  });
  return catalog;
}

async function chapterContent(path) {
  var html = await (await request(source.bookBaseUrl + path, { decode: 'gbk' })).text();
  const $ = load(html);
  //去除script
  $("#content a").remove()
  let content = htmlToString($("#content").html());
  return content;
}

async function testSearchBook() {
  const result = await searchBook('万族之劫', 1);
  console.log("搜索结果：", result);
  return result;
}

async function testBookDetails() {
  const result = await testSearchBook();
  const detatil = await bookDetails(result.bookList[0].path);
  console.log("书籍详情：", detatil);
  return detatil;
}

async function testBookCatalog() {
  const info = await testBookDetails();
  const result = await bookCatalog(info.path);
  console.log("书籍目录：", result);
  return result;
}

async function testChapterContent() {
  const catalog = await testBookCatalog();
  const result = await chapterContent(catalog[0].path);
  console.log("章节内容：", result);
}

await testBookDetails();
// await testChapterContent();
//debugger;

